#include <bits/stdc++.h>

using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution
{
public:
    vector<int> travesal(TreeNode *root)
    {
        vector<int> res;
        if (root == nullptr)
        {
            return res;
        }
        queue<TreeNode *> que;
        que.push(root);
        while (!que.empty())
        {
            int size = que.size();
            for (int i = 0; i < size; i++)
            {
                TreeNode *cur = que.front();
                que.pop();
                res.push_back(cur->val);
                if (cur->left)
                {
                    que.push(cur->left);
                }
                if (cur->right)
                {
                    que.push(cur->right);
                }
            }
        }
        return res;
    }
    // void recursion(TreeNode *root, int& pre)
    // {
    //     if (root == nullptr)
    //     {
    //         return;
    //     }
    //     recursion(root->right, pre);
    //     root->val += pre;
    //     pre = root->val;
    //     recursion(root->left, pre);
    // }
    // TreeNode *convertBST(TreeNode *root)
    // {
    //     int pre = 0;
    //     recursion(root, pre);
    //     return root;
    // }
    void iteration(TreeNode *root, int &pre)
    {
        if (root == nullptr)
        {
            return;
        }
        stack<TreeNode *> stk;
        TreeNode *cur = root;
        while (!stk.empty() || cur != nullptr)
        {
            if (cur != nullptr)
            {
                stk.push(cur);
                cur = cur->right;
            }
            else
            {
                cur = stk.top();
                stk.pop();
                cur->val += pre;
                pre = cur->val;
                cur = cur->left;
            }
        }
    }
    TreeNode *convertBST(TreeNode *root)
    {
        int pre = 0;
        iteration(root, pre);
        return root;
    }
};

int main()
{
    TreeNode *root = new TreeNode(1);
    root->left = new TreeNode(0);
    root->right = new TreeNode(2);
    Solution sol;
    TreeNode *res = sol.convertBST(root);
    vector<int> vec = sol.travesal(res);
    for (auto num : vec)
    {
        cout << num << " ";
    }
    cout << endl;
    return 0;
}